package org.smartjava.concurrent.juc.aqs;

import org.smartjava.util.PrintUtil;
import org.smartjava.util.ThreadUtil;

import java.util.concurrent.Semaphore;

public class SemaphoreExample {

    public static void main(String[] args) {
        //停车位
        Semaphore semaphore = new Semaphore(3, false);

        for (int i = 0; i < 6; i++) {
            new Thread(() -> {
                long time = 0;
                try {
                    semaphore.acquire();
                    PrintUtil.print(ThreadUtil.threadName() + "抢到车位");
                    //模拟停车几个小时
                    time = ThreadUtil.sleepRandom(3) + 1;
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                } finally {
                    PrintUtil.print(ThreadUtil.threadName(), "离开车位，占用时间", time, "小时");
                    semaphore.release();
                }
            }, "Car" + i).start();
        }
    }
}
